package com.sc.nft.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.sc.nft.dao.DigitalCollectionProductInfoDao;
import com.sc.nft.entity.DigitalCollectionProductInfo;
import com.sc.nft.entity.StaticData;
import com.sc.nft.service.DigitalCollectionProductInfoService;
import com.sc.nft.service.StaticDataService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
@Slf4j
public class OpenPpurchaseTask {


    private final DigitalCollectionProductInfoService digitalCollectionProductInfoService;
    private final DigitalCollectionProductInfoDao digitalCollectionProductInfoDao;
    private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    @XxlJob("openProductBegin")
    public void openProductBegin() throws Exception {
        DateTime offset = DateTime.now().offset(DateField.SECOND, 30);//未来30秒
        //查询所有productType=4 (未开启) status=1(上架中) IsSoldOut=0(未售罄)的商品
        List<DigitalCollectionProductInfo> list = digitalCollectionProductInfoDao.getAllNoBeginProduct(offset);
        for (DigitalCollectionProductInfo productInfo : list) {
            try{
                long delayInSeconds = calculateDelayInSeconds(productInfo.getBeginTime());
                executor.schedule(() -> digitalCollectionProductInfoService.autoOpenProductBegin(productInfo), delayInSeconds, TimeUnit.SECONDS);
            }catch (Exception e){
                log.error("开启商品失败:",e);
            }
        }

    }

    @XxlJob("closeProductEnd")
    public void closeProductEnd() throws Exception {
        digitalCollectionProductInfoService.closeProductEnd();
    }


    private long calculateDelayInSeconds(Date completeTime) {
        long currentTime = System.currentTimeMillis();
        long targetTime = completeTime.getTime();
        return (targetTime - currentTime) / 1000; // 转换为秒
    }
}
